﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Enter.Services.DataCache;
using Enter.Services.Mail;
using Enter.Mvc.Base.Controllers;
using System.Web.Mvc;
using Enter.Entity;
using Enter.Mvc.Mall.Model.Product;
using Newtonsoft.Json;
using Enter.Config;
using System.Collections.Specialized;
using Enter.Mvc.Mall.Model.User;
using System.Web;
using Enter.Common;

namespace Enter.Mvc.Mall.Controllers
{
  public  class AuctionController: BaseControllers
    {
       private readonly ICache icache;
        private readonly IMail imail;

        public AuctionController(ICache cache, IMail mail)
        {
            this.icache = cache;
            this.imail = mail;
        }

     #region 我要买-商品类别
        public ViewResult sell()
      {
          List<T105_GoodClassEntity> all = GetGoodCategory();
          List<T105_GoodClassEntity> list =all.FindAll(model => model.ParentID=="0");

          List<CategoryListModel> CategoryList = null;
          if (list != null && list.Count > 0)
          {
              CategoryList = new List<CategoryListModel>();
              foreach(T105_GoodClassEntity entity in list)
              {
                  CategoryListModel model = new CategoryListModel();
                  CategoryModel category = new CategoryModel();
                  category.CNO = entity.CNO;
                  category.CName = entity.CName;
                  category.ChinesePy = entity.ChinesePy;
                  model.Category = category;
                  List<CategoryModel> categorylist = null;
                  List<T105_GoodClassEntity> clist = all.FindAll(cmodel => cmodel.ParentID == entity.CNO);
                  if (clist != null && clist.Count > 0)
                  {
                      categorylist = new List<CategoryModel>();
                      foreach (T105_GoodClassEntity centity in clist)
                      {
                          CategoryModel c = new CategoryModel();
                          c.CNO = centity.CNO;
                          c.CName = centity.CName;
                          c.ChinesePy = centity.ChinesePy;
                          categorylist.Add(c);
                      }
                  }
                  model.ChildCategorys = categorylist;
                  CategoryList.Add(model);
              }
          }
          return View(CategoryList);
      }
        public ActionResult GetCategory(string CateNO)
        {
            List<T105_GoodClassEntity> all = GetGoodCategory();
            List<T105_GoodClassEntity> list = all.FindAll(model => model.ParentID == CateNO);
            List<CategoryModel> categorylist = null;
            if (list != null && list.Count > 0)
            {
                categorylist = new List<CategoryModel>();
                foreach (T105_GoodClassEntity centity in list)
                {
                    CategoryModel c = new CategoryModel();
                    c.CNO = centity.CNO;
                    c.CName = centity.CName;
                    c.ChinesePy = centity.ChinesePy;
                    c.IsParent = centity.IsParent;
                    categorylist.Add(c);
                }
            }
            object obj = new { list = categorylist };

            string result = JavaScriptConvert.SerializeObject(obj);
            return Content(result);
        }
        public ActionResult GetBrand(string CateNO)
        {
            List<T109_GoodBrandEntity>  list= imail.GetGoodBrandbyCateNO(CateNO);
            List<BrandModel> Brands=null;
            if (list != null && list.Count > 0)
            {
                Brands = new List<BrandModel>();
                foreach (T109_GoodBrandEntity entity in list)
                {
                    BrandModel model = new BrandModel();
                    model.BNO = entity.BNO;
                    model.BName = entity.BName;
                    Brands.Add(model);
                }
            }
            object obj = new { list = Brands };

            string result = JavaScriptConvert.SerializeObject(obj);
            return Content(result);
        }
      private List<T105_GoodClassEntity> GetGoodCategory()
      {
         
          string key = "sssssdas";
          List<T105_GoodClassEntity> list = icache.Get<List<T105_GoodClassEntity>>(key);
          if (list == null)
          {
              list = imail.GetAllGoodClassList();
              list.Sort(CompareDinosByName);
              icache.Put(key, list);
          }
          
          return list;
      }
      private static int CompareDinosByName(T105_GoodClassEntity x, T105_GoodClassEntity y)
      {
          if (x == null)
          {
              if (y == null)
              {
                  // If x is null and y is null, they're
                  // equal. 
                  return 0;
              }
              else
              {
                  // If x is null and y is not null, y
                  // is greater. 
                  return -1;
              }
          }
          else
          {
              // If x is not null...
              //
              if (y == null)
              // ...and y is null, x is greater.
              {
                  return 1;
              }
              else
              {
                  // ...and y is not null, compare the 
                  // lengths of the two strings.
                  //
                  int retval = x.CName.CompareTo(y.CName);

                  if (retval != 0)
                  {
                      // If the strings are not of equal length,
                      // the longer string is greater.
                      //
                      return retval;
                  }
                  else
                  {
                      // If the strings are of equal length,
                      // sort them with ordinary string comparison.
                      //
                      return 0;
                  }
              }
          }
      }
        #endregion

      #region 商品属性

      //public ViewResult publish(string CateNO, string BrandNo)
      //{

      //    return View();
      //}
      public ViewResult publish()
      {
          string CateNO = "01010201";
          string bNo = "278";

          ViewData["cat"] = CateNO;

          List<T106_GoodClassPropertyEntity> plist = imail.GetClassPropertyList(CateNO);
        List<Property_Value> pvlist = null;


        #region 品牌
        Property_Value brank = GetBrank(CateNO, bNo);
        if (brank != null)
        {
            if (pvlist == null)
            {
                pvlist = new List<Property_Value>();
            }
            pvlist.Add(brank);
        }

        #endregion
        #region 基本属性
        if (plist!=null&&plist.Count>0)
          {
              if (pvlist == null)
              {
                  pvlist = new List<Property_Value>();
              }
              foreach(T106_GoodClassPropertyEntity p in plist)
              {
                  Property_Value pv = new Property_Value();
                  PropertyModel pm = new PropertyModel();
                  pm.PNo = p.PNo;
                  pm.PName = p.PName;
                  pm.IsRequired = p.IsRequired;
                  pm.chooseType = (Enter.Mvc.Mall.Model.Product.PropertyModel.EnumchooseType)(byte)(p.chooseType);
                  pm.PorpertyType = EnumProductPorpertyType.Base;
                  pv.PropertyName = pm;

                  if (pm.chooseType != Enter.Mvc.Mall.Model.Product.PropertyModel.EnumchooseType.Input)
                  {
                      List<PropertyValueModel> vs = null;
                      List<T116_GoodClassProperty_ValueEntity> vlist= imail.GetPrpertyValue(pm.PNo);
                      if (vlist != null && vlist.Count > 0)
                      {
                          vs = new List<PropertyValueModel>();

                          foreach (T116_GoodClassProperty_ValueEntity v in vlist)
                          {
                              PropertyValueModel vm = new PropertyValueModel();
                              vm.VNO = v.VNO;
                              vm.VName = v.VName;
                              vm.PNo = v.PNo;
                              vs.Add(vm);
                          }
                          pv.PropertyValues = vs;
                      }
                      else {
                          pv.PropertyValues = null;
                      }
                  }

                  pvlist.Add(pv);
              }
          }
        #endregion

      

          #region 库存
          List<Property_Value> Stocklist = GetStock(CateNO);
          if (Stocklist != null)
          {
              if (pvlist == null)
              {
                  pvlist = new List<Property_Value>();
              }
              pvlist.AddRange(Stocklist);
          }
          #endregion



             
          return View(pvlist);
      }
      private Property_Value GetBrank(string CateNO,string bNo)
      {
          Property_Value pv = null;
          List<T109_GoodBrandEntity> list = imail.GetGoodBrandbyCateNO(CateNO);

          if (list != null && list.Count > 0)
          {
               pv = new Property_Value();
              PropertyModel pm = new PropertyModel();
              pm.PNo = "brand";
              pm.PName = "品牌";
              pm.IsRequired = true;
              pm.chooseType = Enter.Mvc.Mall.Model.Product.PropertyModel.EnumchooseType.Radio;
              pm.PorpertyType = EnumProductPorpertyType.Brand;
              pv.PropertyName = pm;
              List<PropertyValueModel> vs = new List<PropertyValueModel>();
              foreach (T109_GoodBrandEntity entity in list)
              {
                  PropertyValueModel vm = new PropertyValueModel();
                  vm.VNO = entity.BNO;
                  vm.VName = entity.BName;
                  vm.PNo = pm.PNo;
                  if (vm.VNO == bNo)
                  {
                      vm.Selected = true;
                  }
                  vs.Add(vm);
              }
              pv.PropertyValues = vs;
          }
          return pv;
      }

      private List<Property_Value> GetStock(string CateNO)
      {
          List<Property_Value> list = null;
         List<T106_GoodClassStockPropertyEntity> StockList= imail.GetStockProperty(CateNO);
         if (StockList!=null)
          {
              list = new List<Property_Value>();

              List<T106_GoodClassStockPropertyEntity> colorList = StockList.FindAll(model => model.ProType == T106_GoodClassStockPropertyEntity.EnumProType.Color);
             
             
             if (colorList != null && colorList.Count > 0)
              {

                  list.Add(GetStock(colorList, EnumProductPorpertyType.Color));
              }
             List<T106_GoodClassStockPropertyEntity> sizeList = StockList.FindAll(model => model.ProType == T106_GoodClassStockPropertyEntity.EnumProType.Size);
             if (sizeList != null && sizeList.Count > 0)
             {

                 list.Add(GetStock(sizeList, EnumProductPorpertyType.Size));
             }
          }
         return list;
      }
      private Property_Value GetStock(List<T106_GoodClassStockPropertyEntity> list, EnumProductPorpertyType type)
      {
          Property_Value pv = new Property_Value();
          PropertyModel pm = new PropertyModel();
          switch (type)
          {
              case EnumProductPorpertyType.Color:  
                  pm.PNo = "Color-";
                  pm.PName = "颜色";
                  break;
              case EnumProductPorpertyType.Size:
                  pm.PNo = "Size-";
                  pm.PName = "尺码";
                  break;
          }
          pm.chooseType = Enter.Mvc.Mall.Model.Product.PropertyModel.EnumchooseType.Multiple;
          pm.IsRequired = true;
         
          pm.PorpertyType = type;


          List<PropertyValueModel> vs = new List<PropertyValueModel>();
          foreach (T106_GoodClassStockPropertyEntity entity in list)
          {
              PropertyValueModel vm = new PropertyValueModel();
              vm.VNO = entity.PNo;
              vm.VName = entity.PName;
              vm.PNo = entity.ParentNO;
              pm.PNo += entity.ParentNO;
              vm.Color = entity.Color;
              vs.Add(vm);
          }
          pv.PropertyName = pm;
          pv.PropertyValues = vs;
          return pv;
      }
      #endregion


      #region 上传图片
      public ActionResult productuploadImg()
      {
          return View();
      }
      #endregion

      #region 上传商品
      public ActionResult AddPrpductForm()
      {

          try
          {
              string NO= imail.GetProductNo();

              List<T113_Good_PropertyEntity> PropertyList = new List<T113_Good_PropertyEntity>();

              NameValueCollection coll;


              coll = Request.Form;

              String[] AllKeys = coll.AllKeys;
              string[] color = null; 
              string[] size=null;
              string[] imges=null;

              #region 属性

              string brand = Request.Form["brand"].ToString();
              if (string.IsNullOrEmpty(brand))
              {
                  throw new ArgumentException("请选择品牌");
              }
              else
              {
                  T113_Good_PropertyEntity entity = new T113_Good_PropertyEntity();
                  entity.GNo = NO;
                  entity.PropertyNO = "00";
                  entity.PropertyValue = brand;
                  entity.PropertyType = EnumProductPorpertyType.Base;
                  PropertyList.Add(entity);
              }

              for (int i = 0; i < AllKeys.Length; i++)
              {
                  string key = AllKeys[i];
                  string value = Request.Form[i];
                  string[] p = key.Split('-');
                 
                  if (p.Length > 0 && !string.IsNullOrEmpty(value))
                  {
                      if (p[0] == "cp")
                      {
                          T113_Good_PropertyEntity entity = new T113_Good_PropertyEntity();
                          entity.GNo = NO;
                          entity.PropertyNO = p[1];
                          entity.PropertyValue = value;
                          entity.PropertyType = EnumProductPorpertyType.Base;
                          
                          if (value.Contains(","))
                          {
                              foreach (string v in value.Split(','))
                              {
                                  T113_Good_PropertyEntity entity1 = new T113_Good_PropertyEntity();
                                  entity1.GNo = NO;
                                  entity1.PropertyNO = p[1];
                                  entity1.PropertyValue = value;
                                  entity1.PropertyType = EnumProductPorpertyType.Base;
                                  entity1.PropertyValue = v;
                                  PropertyList.Add(entity1);
                              }
                          }
                          else {
                              entity.PropertyValue = value;
                              PropertyList.Add(entity);
                          }
                      }
                      else if (p.Length > 0 && p[0] == "ccp")
                      {
                          color=value.Split(',');
                      }
                      else if (p.Length > 0 && p[0] == "scp")
                      {
                           size = value.Split(',');
                      }
                  }
                  if (key == "PicField")
                  {
                      imges=value.Split(',');
                  }
              }
            
#endregion  
               List<T103_Goods_ItemEntity> item = new List<T103_Goods_ItemEntity>();
              #region 库存
             

              if (color != null && size != null && color.Length > 0 && size.Length > 0)
              {
                  for (int i = 0; i < color.Length; i++)
                  {
                      string cNo = color[i];
                      string k = "cpvf-" + cNo;

                      string imgurl = "";
                      string cName = Request.Form["ccpva-" + cNo].ToString();
                      //HttpPostedFileBase FUpload = HttpContext.Request.Files[k] as HttpPostedFileBase;
                      //if (FUpload.ContentLength > 0)
                      //{
                      //    imgurl = "";
                      //}
                      for (int j = 0; j < size.Length; j++)
                      {

                          string sNo = size[j];
                          string sName = Request.Form["scpva-" + sNo].ToString();
                          string scno = cNo + "-" + sNo;

                          decimal price = RequestStrHelper.GetDecimalFromRequest("p-" + scno);
                          int Quantity =RequestStrHelper.GetIntFromRequest("q-" + scno);
                          if (price > 0 && Quantity > 0)
                          {
                              T103_Goods_ItemEntity stock = new T103_Goods_ItemEntity();
                              stock.ColorName = cName;
                              stock.ColorNO = cNo;
                              stock.SizeNO = sNo;
                              stock.SizeName = sName;
                              stock.GSTOCKS = Quantity;
                              stock.PSalePRICE = price;
                              stock.PGNo = NO + "-" + scno;
                              stock.GNo = NO;
                              item.Add(stock);
                          }
                      }
                  }
              }
              else if (color != null&&color.Length > 0)
              {
                  for (int i = 0; i < color.Length; i++)
                  {
                      string cNo = color[i];
                      string k = "cpvf-" + cNo;

                      string imgurl = "";
                      string cName = Request.Form["ccpva-" + cNo].ToString();
                      //HttpPostedFileBase FUpload = HttpContext.Request.Files[k] as HttpPostedFileBase;
                      //if (FUpload.ContentLength > 0)
                      //{
                      //    imgurl = "";
                      //}
                          string scno = cNo;
                          decimal price = RequestStrHelper.GetDecimalFromRequest("p-" + scno);
                          int Quantity = RequestStrHelper.GetIntFromRequest("q-" + scno);
                           if (price > 0 && Quantity > 0)
                          
                          {
                              T103_Goods_ItemEntity stock = new T103_Goods_ItemEntity();
                              stock.ColorName = cName;
                              stock.ColorNO = cNo;

                              stock.GSTOCKS = Quantity;
                              stock.PSalePRICE = price;
                              stock.PGNo = NO + "-" + scno;
                              stock.GNo = NO;
                              item.Add(stock);
                          }
                      
                  }
              }
              else if (size != null && size.Length > 0)
              {
                  for (int j = 0; j < size.Length; j++)
                  {

                      string sNo = size[j];
                      string sName = Request.Form["scpva-" + sNo].ToString();
                      string scno = sNo;
                      decimal price = RequestStrHelper.GetDecimalFromRequest("p-" + scno);
                      int Quantity = RequestStrHelper.GetIntFromRequest("q-" + scno);
                      if (price > 0 && Quantity > 0)
                      {
                          T103_Goods_ItemEntity stock = new T103_Goods_ItemEntity();
                          stock.SizeNO = sNo;
                          stock.SizeName = sName;
                          stock.GSTOCKS = Quantity;
                          stock.PSalePRICE = price;
                          stock.PGNo = NO + "-" + scno;
                          stock.GNo = NO;
                          item.Add(stock);
                      }
                  }
              }


              #endregion

              List<T104_GoodImgesEntity> imageslist = new List<T104_GoodImgesEntity>();
              string productListimg = "";
              string productListSmallimg = "";
              #region 图片
              if (imges != null &&  imges.Length > 0)
              {
                  int i = 1;
                  foreach (string img in imges)
                 {
                     if (!string.IsNullOrEmpty(img))
                     {
                         string oldpath = ImgPathConfig.productUploadPath;
                         string UploadPath, ServerPath;
                         int width = 0, height = 0, size1 = 0;
                         string imgFullPath="";

                        
                         if (i == 1)
                         {
                             #region 列表页
                         T104_GoodImgesEntity imagemodel = new T104_GoodImgesEntity();
                         imagemodel.GNO = NO;
                         imagemodel.ImgUrl = img;
                         imagemodel.Status = EnumStatus.Valid;
                         imagemodel.PageType = 1;
                         imagemodel.imgType = ImgRootType.product_list;
                         imail.GetUploadPath(imagemodel.imgType, out UploadPath, out ServerPath, out  width, out  height, out  size1);
                         ImgHelper.CreateImg(oldpath + img, UploadPath, ((int)imagemodel.imgType).ToString(), width, height, out imgFullPath);
                          imagemodel.SmallImgUrl = imgFullPath;
                         
                              productListimg = imgFullPath;
                          
                          imageslist.Add(imagemodel);

  #endregion

                          #region 热门排行
                          T104_GoodImgesEntity imagemodel5 = new T104_GoodImgesEntity();
                          imagemodel5.GNO = NO;
                          imagemodel5.ImgUrl = img;
                          imagemodel5.PageType = 1;
                          imagemodel5.Status = EnumStatus.Valid;
                          imagemodel5.imgType = ImgRootType.product_hotbank;
                          imail.GetUploadPath(imagemodel5.imgType, out UploadPath, out ServerPath, out  width, out  height, out  size1);
                          ImgHelper.CreateImg(oldpath + img, UploadPath, ((int)imagemodel5.imgType).ToString(), width, height, out imgFullPath);
                          imagemodel5.SmallImgUrl = imgFullPath;
                        
                          
                          
                          imageslist.Add(imagemodel5);
                          #endregion
                         }
                         

                          #region 商品原图
                          T104_GoodImgesEntity imagemodel1 = new T104_GoodImgesEntity();
                          imagemodel1.GNO = NO;
                          imagemodel1.ImgUrl = img;
                          imagemodel1.Status = EnumStatus.Valid;
                          imagemodel1.PageType = i;
                          imagemodel1.imgType = ImgRootType.product;
                          imageslist.Add(imagemodel1);

                          #endregion
                          #region 商品详情
                          T104_GoodImgesEntity imagemode3 = new T104_GoodImgesEntity();
                          imagemode3.GNO = NO;
                          imagemode3.ImgUrl = img;
                          imagemode3.Status = EnumStatus.Valid;
                          imagemode3.PageType = i;
                          imagemode3.imgType = ImgRootType.product_info_big;

                          imail.GetUploadPath(ImgRootType.product_info_big, out UploadPath, out ServerPath, out  width, out  height, out  size1);
                          ImgHelper.CreateImg(oldpath + img, UploadPath, ((int)ImgRootType.product_info_big).ToString(), width, height, out imgFullPath);
                          imagemode3.ImgUrl = imgFullPath;

                          imail.GetUploadPath(ImgRootType.product_info_small, out UploadPath, out ServerPath, out  width, out  height, out  size1);
                          ImgHelper.CreateImg(oldpath + img, UploadPath, ((int)ImgRootType.product_info_small).ToString(), width, height, out imgFullPath);
                          
                         
                         imagemode3.SmallImgUrl = imgFullPath;

                          imageslist.Add(imagemode3);
                         if(i==0)
                         {
                             productListSmallimg = imgFullPath;
                         }
                          #endregion
                          i++;
                     }

                    
                 }
              }
              #endregion

              T101_GoodsEntity Good = new T101_GoodsEntity();
              Good.GNo = NO;
              Good.GShopNO = UserInfo.CurrentUser.ShopNo;
              Good.GAreaNO = UserInfo.CurrentUser.AreaNo;
              Good.GBegTime = DateTime.Now;
              Good.GClassNo =RequestStrHelper.GetStringFromRequest("cat");
              Good.GContent = "";
              Good.GEndTime = DateTime.Now.AddYears(1);
              Good.GSalePRICE =RequestStrHelper.GetDecimalFromRequest("SalePRICE");
              Good.GSTOCKS = RequestStrHelper.GetIntFromRequest("STOCKS");
              Good.ImgUrl = productListimg;
              Good.SmallImgUrl = productListSmallimg;
              Good.GTitle = RequestStrHelper.GetStringFromRequest("Title");


              imail.AddProduct(Good, item, imageslist, PropertyList);
            

          }
          catch (Exception ex)
          {

              throw;
          }
          return View();
      }
      #endregion
    }
}
